<template>
    <div class="profile">
        <div class="pic">
            <div class="block"><el-avatar :size="84" :src="imageUrl ? imageUrl : defaultProfile"></el-avatar></div>
        </div>
        <el-upload class="upload" action="" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-change="uploadChange" :auto-upload="false"
            accept=".jpg, .png">
            <el-button type="primary" size="mini">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-upload>
    </div>
</template>

<script>
import { compressImgToBase64 } from '@/utils/fileUtils'
import defaultProfile from '@/assets/imgs/defaultProfile.png'
export default {
    props: {
        imageUrl: {
            type: String,
            required: false
        }
    },
    data() {
        return {
            defaultProfile,
        }
    },
    methods: {
        beforeAvatarUpload(file) {
            let isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
        },
        uploadChange(file,fileList){
            compressImgToBase64(file.raw).then(base64Url=>{
                this.defaultProfile = base64Url;
            }).catch(err=>{
                this.$message.error(err);
            })
        }
    }
}
</script>

<style scoped lang="scss">
.profile {
    display: flex;
    flex-direction: row;
    align-items: flex-end;

    .upload {
        margin-left: 15px;
    }
}
</style>